const { user, User } = require('../../model/user')
const bcrypt = require('bcrypt');

module.exports = async(req, res, next) => {
    const body = req.body
    const id = req.query.id

    let user = await User.findOne({ _id: id })

    const isValid = await bcrypt.compare(req.body.password, user.password)
    if (isValid) {
        //密码比对成功

        //更新
        await User.updateOne({ _id: id }, {
            username: req.body.username,
            email: req.body.email,
            role: req.body.role,
            state: req.body.state
        })

        //重定向到用户列表
        res.redirect('/admin/user')
    } else {
        //比对失败
        let obj = { path: '/admin/user-edit', message: '密码错误，修改失败', id: id }
        next(JSON.stringify(obj))
    }
}